const { useState, useEffect } = React;

function OrderManagement() {
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [selectedTime, setSelectedTime] = useState('');
    const [downloading, setDownloading] = useState(null);
    const [pagination, setPagination] = useState({
        currentPage: 0,
        totalPages: 0,
        totalElements: 0,
        size: 20
    });

    // 生成时间选项
    const generateTimeOptions = () => {
        const options = [];
        const now = new Date();
        for (let i = 0; i < 24; i++) {
            const time = new Date(now);
            time.setHours(time.getHours() - i);
            options.push({
                value: time.toISOString(),
                label: `${time.getFullYear()}-${String(time.getMonth() + 1).padStart(2, '0')}-${String(time.getDate()).padStart(2, '0')} ${String(time.getHours()).padStart(2, '0')}:00`
            });
        }
        return options;
    };

    const fetchOrders = async (page = 0) => {
        const token = CONFIG.state.getAdminToken();
        if (!token) {
            setError('请先登录');
            window.location.href = '/admin/login.html';
            return;
        }

        setLoading(true);
        setError('');

        try {
            const response = await fetch(`${CONFIG.API_BASE_URL}${CONFIG.API_ENDPOINTS.SEARCH_ORDERS}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    token,
                    payment_time: selectedTime || null,
                    page,
                    size: pagination.size
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            if (data.code === 200) {
                setOrders(data.data.content);
                setPagination({
                    currentPage: data.data.currentPage,
                    totalPages: data.data.totalPages,
                    totalElements: data.data.totalElements,
                    size: data.data.size
                });
            } else {
                setError(data.message || '获取订单失败');
                if (data.code === 401) {
                    window.location.href = '/admin/login.html';
                }
            }
        } catch (err) {
            console.error('Fetch orders error:', err);
            setError('获取订单失败：' + err.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchOrders();
    }, [selectedTime]);

    const handleTimeChange = (e) => {
        setSelectedTime(e.target.value);
    };

    const handlePageChange = (page) => {
        fetchOrders(page);
    };

    const formatAddress = (order) => {
        if (!order.province && !order.city && !order.district && !order.detailAddress) {
            return '无地址信息';
        }
        return `${order.province || ''} ${order.city || ''} ${order.district || ''} ${order.detailAddress || ''} (${order.consignee || ''} ${order.phoneNumber || ''})`;
    };

    const formatPhotoCount = (photos) => {
        if (!photos || photos.length === 0) {
            return '无照片';
        }
        return `${photos.length} 张照片`;
    };

    const downloadPhotos = async (orderId) => {
        if (!window.showDirectoryPicker) {
            alert('您的浏览器不支持此功能，请使用最新版本的Chrome或Edge浏览器');
            return;
        }

        try {
            setDownloading(orderId);

            // 获取照片URL列表
            const token = CONFIG.state.getAdminToken();
            const response = await fetch(`${CONFIG.API_BASE_URL}/api/admin/download-photos`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    token,
                    orderId
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            if (data.code !== 200) {
                throw new Error(data.message || '获取照片列表失败');
            }

            // 让用户选择保存目录
            const dirHandle = await window.showDirectoryPicker();
            
            // 创建订单ID文件夹
            const orderDirHandle = await dirHandle.getDirectoryHandle(`order_${orderId}`, { create: true });

            // 下载所有照片
            for (const photo of data.data) {
                const response = await fetch(photo.imageUrl);
                const blob = await response.blob();
                const fileHandle = await orderDirHandle.getFileHandle(photo.fileName, { create: true });
                const writable = await fileHandle.createWritable();
                await writable.write(blob);
                await writable.close();
            }

            alert('照片下载完成！');
        } catch (err) {
            console.error('Download photos error:', err);
            alert('下载失败：' + err.message);
        } finally {
            setDownloading(null);
        }
    };

    const handleSearch = () => {
        fetchOrders();
    };

    return (
        <div className="container">
            <div className="header">
                <h2>订单管理</h2>
                <div className="search-bar">
                    <div className="input-group">
                        <label>支付时间：</label>
                        <input
                            type="text"
                            value={selectedTime}
                            onChange={(e) => setSelectedTime(e.target.value)}
                            placeholder="格式：yyyy-MM-dd HH"
                            className="time-input"
                        />
                    </div>
                    <button onClick={handleSearch} disabled={loading}>
                        搜索
                    </button>
                </div>
            </div>

            {error && <div className="error-message">{error}</div>}

            <div className="table-container">
                <table className="order-table">
                    <thead>
                        <tr>
                            <th>订单ID</th>
                            <th>支付时间</th>
                            <th>实付金额</th>
                            <th>订单状态</th>
                            {/* <th>用户ID</th> */}
                            <th>收货地址</th>
                            <th>照片数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {loading ? (
                            <tr>
                                <td colSpan="8" className="loading">加载中...</td>
                            </tr>
                        ) : error ? (
                            <tr>
                                <td colSpan="8" className="error">{error}</td>
                            </tr>
                        ) : orders.length === 0 ? (
                            <tr>
                                <td colSpan="8" className="no-data">暂无数据</td>
                            </tr>
                        ) : (
                            orders.map(order => (
                                <tr key={order.orderId}>
                                    <td>{order.orderId}</td>
                                    <td>{new Date(order.paymentTime).toLocaleString()}</td>
                                    <td>￥{order.actualAmount}</td>
                                    <td>{order.status}</td>
                                    {/* <td>{order.userId}</td> */}
                                    <td>{formatAddress(order)}</td>
                                    <td>{formatPhotoCount(order.photos)}</td>
                                    <td>
                                        {order.photos && order.photos.length > 0 && (
                                            <button 
                                                onClick={() => downloadPhotos(order.orderId)}
                                                disabled={downloading === order.orderId}
                                                className="download-btn"
                                            >
                                                {downloading === order.orderId ? '下载中...' : '下载照片'}
                                            </button>
                                        )}
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {!loading && orders.length > 0 && (
                <div className="pagination">
                    <button 
                        onClick={() => handlePageChange(0)} 
                        disabled={pagination.currentPage === 0}
                    >
                        首页
                    </button>
                    <button 
                        onClick={() => handlePageChange(pagination.currentPage - 1)}
                        disabled={pagination.currentPage === 0}
                    >
                        上一页
                    </button>
                    <button className="current">
                        {pagination.currentPage + 1} / {pagination.totalPages}
                    </button>
                    <button 
                        onClick={() => handlePageChange(pagination.currentPage + 1)}
                        disabled={pagination.currentPage === pagination.totalPages - 1}
                    >
                        下一页
                    </button>
                    <button 
                        onClick={() => handlePageChange(pagination.totalPages - 1)}
                        disabled={pagination.currentPage === pagination.totalPages - 1}
                    >
                        末页
                    </button>
                </div>
            )}

            <style jsx>{`
                .table-container {
                    margin-top: 20px;
                    overflow-x: auto;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                }
                th, td {
                    padding: 12px;
                    text-align: left;
                    border-bottom: 1px solid #ddd;
                }
                th {
                    background-color: #f5f5f5;
                }
                tr:hover {
                    background-color: #f9f9f9;
                }
                .no-data {
                    text-align: center;
                    color: #999;
                }
                .download-btn {
                    padding: 4px 8px;
                    background-color: #1890ff;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    cursor: pointer;
                    transition: all 0.3s;
                }
                .download-btn:hover {
                    background-color: #40a9ff;
                }
                .download-btn:disabled {
                    background-color: #d9d9d9;
                    cursor: not-allowed;
                }
                .input-group {
                    display: flex;
                    align-items: center;
                    margin-right: 10px;
                }
                .input-group label {
                    margin-right: 8px;
                    white-space: nowrap;
                }
                .time-input {
                    padding: 4px 8px;
                    border: 1px solid #d9d9d9;
                    border-radius: 4px;
                    width: 150px;
                }
                .time-input::placeholder {
                    color: #999;
                    font-size: 12px;
                }
                .time-input:focus {
                    border-color: #40a9ff;
                    outline: none;
                    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
                }
            `}</style>
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('root')).render(<OrderManagement />);
